import { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
  ArrowLeft,
  Download,
  Edit,
  Play,
  Clock,
  Languages,
  Sparkles,
  Save,
  RefreshCw,
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";

import { getAnalysisItem, downloadAnalysis } from "@/api/VideoAnalysis";

interface VideoItem {
  id: string;
  language: string;
  translateLanguage: string;
  videoTime: number;
  videoLineItems: [
    {
      changeText: string;
      endTime: string;
      id: number;
      originalText: string;
      startTime: string;
      translatedText: string;
    }
  ];
}

const ScriptDetail = () => {
  const { videoId } = useParams();
  const navigate = useNavigate();
  const [isRewriting, setIsRewriting] = useState(false);
  const [editingSegment, setEditingSegment] = useState<number | null>(null);
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [dataItem, setDataItem] = useState({
    id: "",
    language: "",
    translateLanguage: "",
    videoTime: 0,
    videoLineItems: [],
  });

  const handleRewriteScript = async () => {
    // setIsRewriting(true);
    // 模拟AI改写
    // setTimeout(() => {
    //   const rewrittenSegments = segments.map((segment) => ({
    //     ...segment,
    //     rewrittenText: segment.translatedText + " [AI改写版本]",
    //   }));
    //   setSegments(rewrittenSegments);
    //   setIsRewriting(false);
    //   toast({
    //     title: "脚本改写完成",
    //     description: "AI已为您重新优化了脚本内容",
    //   });
    // }, 3000);
  };

  const handleDownloadScript = () => {
    if (dataItem.id) {
      downloadAnalysis(dataItem.id);
    }
  };

  const handleSegmentEdit = (index: number, newText: string) => {
    // const updatedSegments = [...segments];
    // updatedSegments[index].rewrittenText = newText;
    // setSegments(updatedSegments);
  };

  const handleSaveEdit = (index: number) => {
    setEditingSegment(null);
    toast({
      title: "保存成功",
      description: `已保存第 ${index + 1} 段的修改`,
    });
  };

  const getDataItem = async (id: string = videoId) => {
    setLoading(true);
    const resdata = await getAnalysisItem(id);
    setLoading(false);
    console.info(resdata);
    const { code, data } = resdata;
    if (code == 200) {
      setDataItem(data);
    } else if (code == 401) {
      navigate("/lgoin");
    } else {
      navigate("/library");
    }
  };

  useEffect(() => {
    getDataItem();
  }, []);
  return (
    <div className="container mx-auto py-8 px-4 max-w-6xl">
      {/* 头部导航 */}
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => navigate("/library")}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回视频库
          </Button>
          <div>
            <h1 className="text-3xl font-bold bg-[var(--gradient-hero)] bg-clip-text text-transparent">
              脚本详情
            </h1>
            <p className="text-muted-foreground mt-1">视频ID: {videoId}</p>
          </div>
        </div>

        <div className="flex gap-2">
          <Button variant="outline" onClick={handleDownloadScript}>
            <Download className="h-4 w-4 mr-2" />
            下载脚本
          </Button>
          <Button
            variant="hero"
            onClick={handleRewriteScript}
            disabled={isRewriting}
          >
            {isRewriting ? (
              <>
                <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                改写中...
              </>
            ) : (
              <>
                <Sparkles className="h-4 w-4 mr-2" />
                改写脚本
              </>
            )}
          </Button>
        </div>
      </div>

      {/* 视频信息概览 */}
      <Card className="mb-6 shadow-[var(--shadow-card)] border-0">
        <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
          <CardTitle className="flex items-center gap-2">
            <Play className="h-5 w-5 text-primary" />
            视频信息
          </CardTitle>
        </CardHeader>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="flex items-center gap-2">
              <Badge variant="secondary">Tiktok</Badge>
              <span className="text-sm text-muted-foreground">平台</span>
            </div>
            <div className="flex items-center gap-2">
              <Languages className="h-4 w-4 text-primary" />
              <span className="text-sm">
                {dataItem.language} → {dataItem.translateLanguage || "中文"}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <Clock className="h-4 w-4 text-primary" />
              <span className="text-sm">总时长: {dataItem.videoTime}</span>
            </div>
            <div className="flex items-center gap-2">
              <Edit className="h-4 w-4 text-primary" />
              <span className="text-sm">
                {dataItem.videoLineItems.length} 个片段
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 脚本内容 */}
      <Card className="shadow-[var(--shadow-card)] border-0">
        <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Languages className="h-5 w-5 text-primary" />
              按时间戳分段脚本
            </div>
            <Badge variant="outline">
              {/* {timeLine.list.filter((s) => s.rewrittenText).length} /{" "}
              {timeLine.list.length} 已改写 */}
            </Badge>
          </CardTitle>
          <CardDescription>
            查看原文、译文和AI改写版本，支持编辑和优化
          </CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          <div className="space-y-0">
            {dataItem.videoLineItems.map((segment, index) => (
              <div key={index} className="p-6 border-b last:border-b-0">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <Badge variant="outline" className="font-mono">
                      {segment.startTime + "~" + segment.endTime}
                    </Badge>
                    <span className="text-sm text-muted-foreground">
                      第 {index + 1} 段
                    </span>
                  </div>
                  {segment.changeText && editingSegment !== index && (
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => setEditingSegment(index)}
                    >
                      <Edit className="h-3 w-3 mr-1" />
                      编辑
                    </Button>
                  )}
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
                  {/* 原文 */}
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 bg-muted rounded-full"></div>
                      <Label className="text-sm font-medium">原文</Label>
                    </div>
                    <div className="p-4 bg-muted/30 rounded-lg">
                      <p className="text-sm leading-relaxed">
                        {segment.originalText}
                      </p>
                    </div>
                  </div>

                  {/* 译文 */}
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 bg-primary rounded-full"></div>
                      <Label className="text-sm font-medium">译文</Label>
                    </div>
                    <div className="p-4 bg-primary/10 rounded-lg">
                      <p className="text-sm leading-relaxed">
                        {segment.translatedText}
                      </p>
                    </div>
                  </div>

                  {/* 改写版本 */}
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <div className="w-3 h-3 bg-success rounded-full"></div>
                      <Label className="text-sm font-medium">AI改写版本</Label>
                    </div>
                    <div className="p-4 bg-success/10 rounded-lg min-h-[80px] flex items-center">
                      {editingSegment === index ? (
                        <div className="w-full space-y-2">
                          <Textarea
                            value={segment.changeText}
                            onChange={(e) =>
                              handleSegmentEdit(index, e.target.value)
                            }
                            placeholder="编辑改写内容..."
                            rows={3}
                            className="resize-none"
                          />
                          <div className="flex gap-2">
                            <Button
                              size="sm"
                              onClick={() => handleSaveEdit(index)}
                            >
                              <Save className="h-3 w-3 mr-1" />
                              保存
                            </Button>
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => setEditingSegment(null)}
                            >
                              取消
                            </Button>
                          </div>
                        </div>
                      ) : (
                        <>
                          {segment.changeText ? (
                            <p className="text-sm leading-relaxed">
                              {segment.changeText}
                            </p>
                          ) : (
                            <div className="text-center w-full">
                              <p className="text-sm text-muted-foreground mb-2">
                                暂未改写
                              </p>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={handleRewriteScript}
                                disabled={isRewriting}
                              >
                                <Sparkles className="h-3 w-3 mr-1" />
                                开始改写
                              </Button>
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default ScriptDetail;
